package com.huatai.datacenter.service.impl;


import com.huatai.common.httputil.HttpRequest;
import com.huatai.common.httputil.ResponseSpec;
import com.huatai.datacenter.config.ServerInfo;
import com.huatai.datacenter.entity.QueryLastMultiple;
import com.huatai.datacenter.entity.QueryLastSingle;
import com.huatai.datacenter.entity.QueryMultiple;
import com.huatai.datacenter.entity.QuerySingle;
import com.huatai.datacenter.service.ResultErrorHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

/**
 * @program: ht-system
 * @description: 数据查询错误处理器
 * @author: songxiude
 * @create: 2023-04-25 15:00
 **/
@Slf4j
@EnableAsync
@Service
public class ResultErrorHandleImpl extends BaseServiceImpl implements ResultErrorHandle {

	@Autowired
	private ServerInfo serverInfo;

	/**
	 * 基础查询的错误处理
	 */
	@Async
	@Override
	public void queryInit(QuerySingle querySingle) {
		String composePut = composePut(querySingle);
		put(composePut);
	}

	/**
	 * 基础查询的错误处理 多设备
	 */
	@Async
	@Override
	public void queryInit(QueryMultiple queryMultiple) {
		String composePut = composePut(queryMultiple);
		put(composePut);
	}

	/**
	 * 查询最新数据的错误处理
	 */
	@Override
	public void queryLastInit(QueryLastSingle queryLastSingle) {
		String composePut = composePut(queryLastSingle);
		put(composePut);
	}

	/**
	 * 基础查询的错误处理 多设备
	 */
	@Async
	@Override
	public void queryLastInit(QueryLastMultiple queryLastMultiple) {
		String composePut = composePut(queryLastMultiple);
		put(composePut);
	}

	/**
	 * 初始化错误数据
	 *
	 * @param composePut 保存的JSON对象
	 */
	private void put(String composePut) {
		String result = HttpRequest.post(serverInfo.getPutUrl())
			.bodyString(composePut)
			.execute()
			.onFailed(((request, e) -> log.error("big data connection error info : " + e.getMessage())))
			.onSuccessOpt(ResponseSpec::asString).orElse("SUCCESS");
		log.info("big data loading finished, msg : " + result);
	}

}
